<?php

namespace App\Console\Commands\Plane;

use App\Models\Plane\Flight\FlightCabin;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class FlightCabinImport extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'flight_cabin:import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入机场舱位数据';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $fc    = new FlightCabin();
        $excel = Excel::toArray(collect(), storage_path('plane/seeds/rc_condition.xlsx'));
        $data  = $excel[0];
        unset($data[0]);

        // 第二步 读取规则
        $excel_rc = Excel::toArray(collect(), storage_path('plane/seeds/rc_rules.xlsx'));
        $datas    = $excel_rc[0];
        unset($datas[0], $datas[1], $datas[2]);
        $column_carrier_code = 1;
        $column_cabin_name   = 7;
        $column_cabins       = 8;
        foreach ($datas as $data) {
            $carrier_code = $data[$column_carrier_code];
            if (mb_strlen($carrier_code) > 2) {
                continue;
            }
            $cabin_name  = $data[$column_cabin_name] ?? '';
            $cabin_codes = $data[$column_cabins] ?: '';
            $cabins      = $this->parse2Cabins($cabin_codes);
            foreach ($cabins as $cabin) {
                if (Str::contains($cabin, '折扣')) {
                    preg_match('/(?<cabin>.+)\((?<discount>\d+%)(?<sign>.*)折扣\)/', $cabin, $res);
                    $cabin = $res['cabin'] ?? $cabin;
                }
                $cabin_code = $this->getCabin($cabin);
                if ($cabin_code && $cabin_name) {
                    try {
                        $fc->add($carrier_code, $cabin_code, $this->getCabinTypeByName($cabin_name));
                    } catch (Exception $e) {

                    }
                }
            }
        }
    }

    private function parse2Cabins($cabin_codes)
    {
        $cabins = [];
        if (!$cabin_codes) {
            return [''];
        }

        $parse  = function ($cabin_codes) {
            $rule   = '/(?<cabin1>[a-zA-Z]+)(?<f>\d)-(?<cabin2>[a-zA-Z]+)(?<l>\d)/s';
            $cabins = [];

            if (preg_match($rule, $cabin_codes, $match)) {
                $range = range($match['f'], $match['l']);
                if ($match['cabin1' == $match['cabin2']]) {
                    $cabins = collect($range)->map(fn($r) => $match['cabin2'].$r)->toArray();
                }

            }
            $splits      = ['/', '\\', '-'];
            $split       = '/';
            $cabin_codes = Str::replace($splits, $split, $cabin_codes);
            $exp         = explode($split, $cabin_codes);
            return array_unique(array_merge($cabins, $exp));
        };
        $cabins = $parse($cabin_codes);
        $this->info($cabin_codes.":".json_encode($cabins, 64 | 256));
        return $cabins;
    }

    /**
     */
    function getCabin(string $cabin): string
    {
        if (!$cabin || $cabin == '其他仓位' || $cabin == '无行李特惠') {
            return '';
        }
        preg_match('/[a-zA-Z0-9]+/', $cabin, $match);
        if (empty($match)) {
            return '';
        }
        if (!isset($match[0])) {
            return '';
        }
        return strtoupper($cabin);
    }

    private function getCabinTypeByName(string $cabin_name): int
    {
        if (Str::contains($cabin_name, ['公务', '豪华', '商务', '头等'])) {
            return 1;
        }
        return 2;
    }
}
